package com.wntms.auser.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;
import java.util.Set;

/**
 * JWT工具类
 */
public class JwtUtils {
    private static final int TIME = 60*60*24*7;
    private static final String SIGN = "adsfjj!3sad";

    /**
     * 获取token
     * @param map 存储载荷中的数据
     * @return 字符串的token
     */
    public static String getToken(Map<String, String> map) {
        JWTCreator.Builder builder = JWT.create();

        //设置header
        /*
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");
        builder..withHeader(map);
        */

        //设置payload
        Set<String> set = map.keySet();
        for (String key : set) {
            String value = map.get(key);
            builder.withClaim(key, value);
        }

        //设置过期时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, TIME);
        builder.withExpiresAt(calendar.getTime());

        //设置signature
        String token = builder.sign(Algorithm.HMAC256(SIGN));

        return token;
    }

    /**
     * 验证token
     * @param token
     * @return true token有效
     *         false token无效
     */
    public static boolean verify(String token) {
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            return true;
        } catch(Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 解析token
     * @param token
     * @return DecodedJWT对象
     */
    public static DecodedJWT resolverToken(String token) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SIGN)).build();
        DecodedJWT decodedJWT = jwtVerifier.verify(token);
        return decodedJWT;
    }
}
